<script setup>
import { ref, watch, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  queryPageApi as queryStudentPageApi,
  addStudentApi as addStudentApi,
  queryInfoApi as queryStudentInfoApi,
  updateStudentApi as updateStudentApi,
  deleteStudentApi as deleteStudentApi,
  handleDisciplineApi as handleDisciplineApi,
} from "@/api/student";
import { queryClazzPageApi as queryClazzInfoApi } from "@/api/clazz";

//查询全部班级信息
const clazzList = ref([]);
const clazzListQuery = async () => {
  const result = await queryClazzInfoApi(
    "",
    "",
    "",
    page.value,
    pageSize.value
  );
  if (result.code === 200) {
    clazzList.value = result.data.rows.map((item) => ({
      name: item.name,
      value: item.id,
    }));
    console.log("班级信息", clazzList.value);
  } else {
    ElMessage.error("查询班级列表失败：" + result.msg);
  }
};

// 声明 token
const token = ref("");

// 最高学历列表数据
const degrees = ref([
  { name: "初中", value: 1 },
  { name: "高中", value: 2 },
  { name: "大专", value: 3 },
  { name: "本科", value: 4 },
  { name: "硕士", value: 5 },
  { name: "博士", value: 6 },
]);
// 转化最高学历
const getDegreeName = (value) => {
  const degree = degrees.value.find((item) => item.value === value);
  return degree ? degree.name : "";
};

// 性别列表数据
const genders = ref([
  { name: "男", value: 1 },
  { name: "女", value: 2 },
]);

//院校列表数据
const schools = ref([
  { name: "是", value: 1 },
  { name: "否", value: 0 },
]);

// 搜索学生条件
const searchStudent = ref({
  name: "",
  degree: "",
  clazzId: "",
});

onMounted(async () => {
  await clazzListQuery();
  handleSearch();
});

// 加载 localStorage 存储的学生登录信息
const loginUser = localStorage.getItem("user");
if (loginUser) {
  token.value = JSON.parse(loginUser).token;
}

// 查询学生
const handleSearch = async () => {
  const result = await queryStudentPageApi(
    searchStudent.value.name,
    searchStudent.value.degree,
    searchStudent.value.clazzId,
    page.value,
    pageSize.value
  );
  if (result.code === 200) {
    studentList.value = result.data.rows;
    total.value = result.data.total;
  } else {
    ElMessage.error("查询学员表失败：" + result.msg);
  }
};

const handleReset = () => {
  // 清空表单
  searchStudent.value = {
    name: "",
    degree: "",
    clazzId: "",
  };
  handleSearch();
};

// 示例数据
const studentList = ref([]);

// 分页配置
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  page.value = val;
  handleSearch();
};

// 操作处理
const handleEdit = async (id) => {
  const result = await queryStudentInfoApi(id);
  if (result.code === 200) {
    dialogVisible.value = true;
    dialogTitle.value = "修改学生";

    student.value = result.data;
    console.log(student.value);
  } else {
    ElMessage.error("获取学生详情失败：" + result.msg);
  }
};

const disciplineStudent = ref({
  id: null,
  score: 0,
});
const disciplineDialogVisible = ref(false);
// 处理违纪处理
const handleDiscipline = async (id) => {
  const result = await queryStudentInfoApi(id);
  if (result.code === 200) {
    disciplineDialogVisible.value = true;
    disciplineStudent.value.id = result.data.id;
    disciplineStudent.value.score = result.data.violationScore;
  } else {
    ElMessage.error("获取学生详情失败：" + result.msg);
  }
};

// 保存违纪处理信息
const saveDiscipline = async () => {
  const { id, score } = disciplineStudent.value;
  const result = await handleDisciplineApi(id, score);
  if (result.code === 200) {
    ElMessage.success("保存违纪处理信息成功");
    disciplineDialogVisible.value = false;
    handleSearch();
  } else {
    ElMessage.error("保存违纪处理信息失败：" + result.msg);
  }
};

// 删除单个学生
const handleDelete = async (id) => {
  ElMessageBox.confirm("确定删除该学生吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const result = await deleteStudentApi(id);
    if (result.code === 200) {
      ElMessage.success("删除学生成功");
      handleSearch();
    } else {
      ElMessage.error("删除学生失败：" + result.msg);
    }
  });
};

// 新增学生
const addStudent = () => {
  dialogVisible.value = true;
  dialogTitle.value = "新增学员";
  student.value = {
    name: "",
    no: "",
    gender: "",
    phone: "",
    degree: "",
    clazzId: "",
    clazzName: "",
    violationCount: 0,
    violationScore: 0,
    image: "",
    idCard: "",
    isCollege: 0,
    address: "",
    graduationDate: "",
  };
  studentFormRef.value.resetFields();
};

// 新增/修改表单
const studentFormRef = ref(null);
const student = ref({
  name: "",
  no: "",
  gender: "",
  phone: "",
  degree: "",
  clazzId: "",
  clazzName: "",
  violationCount: 0,
  violationScore: 0,
  image: "",
  idCard: "",
  isCollege: 0,
  address: "",
  graduationDate: "",
});

// 表单校验规则
const rules = ref({
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    {
      min: 2,
      max: 10,
      message: "姓名长度应在2到10个字符之间",
      trigger: "blur",
    },
  ],
  no: [
    { required: true, message: "请输入学号", trigger: "blur" },
    {
      min: 2,
      max: 20,
      message: "学号长度应在2到20个字符之间",
      trigger: "blur",
    },
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1\d{10}$/, message: "请输入有效的手机号", trigger: "blur" },
  ],
  idCard: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    {
      min: 18,
      max: 18,
      message: "请输入正确的18位身份证号",
      trigger: "blur",
    },
  ],
  isCollege: [{ required: true, message: "请选择是否院校", trigger: "change" }],
  clazzId: [{ required: true, message: "请选择班级", trigger: "change" }],
});

// 控制弹窗
const dialogVisible = ref(false);
const dialogTitle = ref("新增学员");

// 保存学生信息
const save = async () => {
  studentFormRef.value.validate(async (valid) => {
    if (valid) {
      let result;
      if (student.value.id) {
        // 存在 ID，执行修改操作
        result = await updateStudentApi(student.value);
      } else {
        // 不存在 ID，执行新增操作
        result = await addStudentApi(student.value);
      }
      if (result.code === 200) {
        ElMessage.success("保存学生信息成功");
        dialogVisible.value = false;
        handleSearch();
      } else {
        ElMessage.error("保存学生信息失败：" + result.msg);
      }
    }
  });
};

// 存储选中的 ID
const selectedIds = ref([]);

// 处理复选框选择变化的函数
function handleSelectionChange(selection) {
  const ids = selection.map((item) => item.id);
  selectedIds.value = ids;
}

// 批量删除
const deleteByIds = async () => {
  ElMessageBox.confirm("确定删除选中学生吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const result = await deleteStudentApi(selectedIds.value);
    if (result.code === 200) {
      ElMessage.success("删除学生成功");
      handleSearch();
    } else {
      ElMessage.error("删除学生失败：" + result.msg);
    }
  });
};
</script>

<template>
  <h1>学生管理</h1>
  <br />
  <el-form :inline="true" :model="searchStudent" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input
        size="large"
        v-model="searchStudent.name"
        placeholder="请输入学生姓名"
        style="width: 220px"
      ></el-input>
    </el-form-item>

    <el-form-item label="最高学历">
      <el-select
        v-model="searchStudent.degree"
        placeholder="请选择"
        size="large"
        style="width: 250px"
      >
        <el-option
          v-for="level in degrees"
          :key="level.value"
          :label="level.name"
          :value="level.value"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="所属班级">
      <el-select
        v-model="searchStudent.clazzId"
        placeholder="请选择"
        size="large"
        style="width: 250px"
      >
        <el-option
          v-for="clazz in studentList"
          :key="clazz.clazzId"
          :label="clazz.clazzName"
          :value="clazz.clazzId"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">清空</el-button>
    </el-form-item>
  </el-form>

  <el-button type="primary" @click="addStudent"> + 新增学员</el-button>
  <el-button type="danger" @click="deleteByIds"> - 批量删除</el-button>
  <br /><br />

  <!-- 表格 -->
  <el-table
    :data="studentList"
    border
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
    <el-table-column
      type="selection"
      width="55"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="name"
      label="姓名"
      width="120"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="no"
      label="学号"
      width="150"
      align="center"
    ></el-table-column>
    <el-table-column prop="clazzName" label="班级" width="150" align="center">
    </el-table-column>
    <el-table-column label="性别" width="80" align="center">
      <template #default="scope">
        {{ scope.row.gender == 1 ? "男" : "女" }}
      </template>
    </el-table-column>
    <el-table-column
      prop="phone"
      label="手机号"
      width="150"
      align="center"
    ></el-table-column>
    <el-table-column prop="degree" label="最高学历" width="120" align="center">
      <template #default="scope">
        {{ getDegreeName(scope.row.degree) }}
      </template>
    </el-table-column>
    <el-table-column
      prop="violationCount"
      label="违规次数"
      width="120"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="violationScore"
      label="违规扣分"
      width="120"
      align="center"
    >
      <template #default="scope">
        {{ scope.row.violationScore === 0 ? 0 : scope.row.violationScore }}
      </template>
    </el-table-column>
    <el-table-column
      prop="updateTime"
      label="最后修改时间"
      width="210"
      align="center"
    ></el-table-column>
    <el-table-column label="操作" fixed="right" align="center">
      <template #default="scope">
        <el-button size="small" type="primary" @click="handleEdit(scope.row.id)"
          >编辑</el-button
        >
        <el-button
          size="small"
          type="warning"
          @click="handleDiscipline(scope.row.id)"
          >违纪</el-button
        >
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.row.id)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <br />

  <!-- 分页 -->
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="page"
    :page-sizes="[10, 20, 30, 40]"
    :page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
  >
  </el-pagination>

  <!-- 新增/修改学生的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="studentFormRef"
      :model="student"
      :rules="rules"
      label-width="100px"
    >
      <!-- 基本信息 -->
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="student.name"
              placeholder="请输入学生姓名，2-10个字"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="学号" prop="no">
            <el-input
              v-model="student.no"
              placeholder="请输入学生学号，2-20个字"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select
              v-model="student.gender"
              placeholder="请选择性别"
              style="width: 100%"
            >
              <el-option
                v-for="gender in genders"
                :key="gender.value"
                :label="gender.name"
                :value="gender.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="student.phone"
              placeholder="请输入学生手机号"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input
              v-model="student.idCard"
              placeholder="请输入身份证号"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否院校" prop="isCollege">
            <el-select
              v-model="student.isCollege"
              placeholder="请选择是否院校"
              style="width: 100%"
            >
              <el-option
                v-for="isCollege in schools"
                :key="isCollege.value"
                :label="isCollege.name"
                :value="isCollege.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系地址">
            <el-input
              v-model="student.address"
              placeholder="请输入联系地址"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="毕业时间">
            <el-date-picker
              v-model="student.graduationDate"
              type="date"
              placeholder="请选择毕业时间"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="最高学历">
            <el-select
              v-model="student.degree"
              placeholder="请选择最高学历"
              style="width: 100%"
            >
              <el-option
                v-for="level in degrees"
                :key="level.value"
                :label="level.name"
                :value="level.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班级" prop="clazzId">
            <el-select
              v-model="student.clazzId"
              placeholder="请选择所属班级"
              style="width: 100%"
            >
              <el-option
                v-for="clazz in clazzList"
                :key="clazz.value"
                :label="clazz.name"
                :value="clazz.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 违纪处理的对话框 -->
  <el-dialog v-model="disciplineDialogVisible" title="违纪处理">
    <el-form :model="disciplineStudent" label-width="100px">
      <el-form-item label="违规扣分">
        <el-input-number
          v-model="disciplineStudent.score"
          :min="0"
          :max="100"
          controls-position="right"
        ></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="disciplineDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveDiscipline">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
}
</style>
